package com.ambimmort.shj.service.generalfile;

import cn.net.greenet.generalfile.logic.DataChange;
import cn.net.greenet.generalfile.logic.GeneralFileProcess;
import com.ambimmort.shj.action.generalfile.GetAppFromDB2File;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by 师梁 on 2015/7/30.
 */
@Service("getAppFromDB2FileService")
public class GetAppFromDB2FileService {

    public String get(String MessageType,String policy_instance,String dstPath){

        boolean result = false;
        JSONObject one = new JSONObject();
        GeneralFileProcess pro = new GeneralFileProcess(null, MessageType, policy_instance, dstPath);
        String sql = GeneralFileProcess.QUERY_APP;
        //获取文件路径和指定文件名
        pro.getProperties();
        dstPath = pro.getCommonFilePath();
        if (dstPath.endsWith("/")) {
            dstPath = dstPath + pro.getAppTypeName();
        } else {
            dstPath = dstPath + File.separator + pro.getAppTypeName();
        }
        // 获取数据库链接
        pro.init();
        ResultSet rs = pro.query(sql);
        try {
            String name = null;
            String AppType_id = null;
            String appID = null;
            StringBuilder sb = new StringBuilder();
            while (rs != null && rs.next()) {
                int appid = rs.getInt("AppType_id");
                long id = rs.getLong("id");
                name = rs.getString("name");
                AppType_id = DataChange.dec2Hex_2(appid);
                appID = DataChange.dec2Hex_4(id);
                sb.append(name).append("\t").append(AppType_id).append("\t").append(appID);
                if (!rs.isLast()) {
                    sb.append("\n");
                }
            }
            FileUtils.writeStringToFile(new File(dstPath), sb.toString(), false);
            result = true;
        } catch (SQLException ex) {
            Logger.getLogger(GetAppFromDB2File.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //关闭数据库连接
        pro.close();
        one.put("result", result);
        return  one.toString();
    }
}
